package gov.nhso.prov.acc.apps.acc6;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.isud.core.ISUD;
import com.isud.core.ISUDFactory;

import gov.nhso.prov.acc.beans.Acc6ExpenseBean;
import gov.nhso.prov.acc.beans.Acc6TransactionBean;
import gov.nhso.prov.acc.core.DBConnection;
import gov.nhso.prov.acc.utils.Utility;

@SuppressWarnings({"rawtypes","unchecked"})
public class ACC60501 extends Utility{
	public String url = "/apps/acc6/ACC60501A.jsp";
	
	public ACC60501(HttpServletRequest request, HttpServletResponse response) {
		this.message(request).clearMsg();
		String job = this.getAttr(request, "job");
		if(job.equals("init")){
			this.init(request);
		} else if(job.equals("search")){
			this.search(request);
		} else if(job.equals("update")){
			this.update(request);
		}
	}
	
	private String init(HttpServletRequest request){
		Connection conn = null;
		ISUD dao = null;
		try {
			conn = DBConnection.getConnection();
			dao = ISUDFactory.create(conn);
			request.setAttribute("listProvince", this.dataUtil(dao).lsProvince());
			conn.commit();
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException eSQL) {
				eSQL.printStackTrace();
			}
			this.message(request).setMsg("E", e.toString() + ":" + dao.getMessage(), e.getStackTrace());
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				dao = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return this.url;
	}
	private String search(HttpServletRequest request){
		Connection conn = null;
		ISUD dao = null;
		try {
			conn = DBConnection.getConnection();
			dao = ISUDFactory.create(conn);
			
			String provinceId = this.getAttr(request, "provinceId");
			String chequeDate = this.getAttr(request, "chequeDate");
			//String expenseDate = this.getAttr(request, "expenseDate");
			String chequeNo = this.getAttr(request, "chequeNo");
			String status = this.getAttr(request, "status");
			String condition = "";
			List listData = new ArrayList();
			
			Acc6TransactionBean transactionBean = new Acc6TransactionBean();
			transactionBean.setProvinceId(provinceId);
			if (chequeDate != null && !chequeDate.equals("")){
				transactionBean.setChequeDate(this.dateUtil().changeDateToDB(chequeDate));
			}
			transactionBean.setChequeNo(chequeNo);
			//transactionBean.setExpenseDate(this.dateUtil().changeDateToDB(expenseDate));
			transactionBean.setTransactionType("C");
			if(status != null){
				if (status.equals("succeed")){
					condition = " AND CHEQUE_RECEIVING_DATE IS NOT NULL AND REASON_CODE = '00'";
				} else if (status.equals("fail")){
					condition = " AND CHEQUE_RECEIVING_DATE IS NULL ";
				}
			}else{
				status = "";
			}
			condition += " ORDER BY TRANSACTION_TIMESTAMP";
			Map<String, String> xcols = new HashMap<String, String>();
			xcols.put("TRANSACTION_TIMESTAMP", "TO_CHAR(TRANSACTION_TIMESTAMP, 'YYYYMMDDHH24MISSFF3')");
			listData = dao.selectList(transactionBean, xcols, condition);
			
			if(listData.size() == 0){
				this.message(request).setMsgCode("I001");
			}
			request.setAttribute("listData", listData);
			request.setAttribute("provinceId", provinceId);
			request.setAttribute("chequeDate", chequeDate);
			//request.setAttribute("expenseDate", expenseDate);
			request.setAttribute("chequeNo", chequeNo);
			request.setAttribute("status", status);
			request.setAttribute("listProvince", this.dataUtil(dao).lsProvince());
			conn.commit();
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException eSQL) {
				eSQL.printStackTrace();
			}
			this.message(request).setMsg("E", e.toString() + ":" + dao.getMessage(), e.getStackTrace());
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				dao = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return this.url;
	}
	private String update(HttpServletRequest request){
		Connection conn = null;
		ISUD dao = null;
		try {
			conn = DBConnection.getConnection();
			dao = ISUDFactory.create(conn);
			String[] transactionTimestamp = request.getParameterValues("transactionTimestamp");
			String[] chequeReceivingDate = request.getParameterValues("chequeReceivingDate");
			Acc6TransactionBean transactionBean = new Acc6TransactionBean();
			Map<String, String> mapDocNoY = new HashMap<String, String>();
			String docNo = "";
			Map<String, String> data = new HashMap<String, String>();
			if (chequeReceivingDate != null && transactionTimestamp != null){
				for (int i=0;i<transactionTimestamp.length;i++){
					if (!chequeReceivingDate[i].equals("")){
						transactionBean.setReasonCode("00");
						transactionBean.setChequeReceivingDate(this.dateUtil().changeDateToDB(chequeReceivingDate[i]));
						transactionBean.setTransactionTimestamp(this.dateUtil().setTimeStamp2DB(transactionTimestamp[i]));
						dao.update(transactionBean);
						dao.execDataSql("UPDATE "+ this.schema + ".ACC6_EXPENSE_CHEQUE SET CHEQUE_RECEIVING_DATE = "+this.dateUtil().changeDateToDB(chequeReceivingDate[i])+" WHERE TRANSACTION_TIMESTAMP = " + this.dateUtil().setTimeStamp2DB(transactionTimestamp[i]));
						data = dao.findDataSql("SELECT DOC_NO  FROM " + this.schema + ".ACC6_EXPENSE_CHEQUE WHERE TRANSACTION_TIMESTAMP = " + this.dateUtil().setTimeStamp2DB(transactionTimestamp[i]));
						docNo = dao.chkData(data.get("DOC_NO"));
						if (!dao.chkData(mapDocNoY.get(docNo)).equals("")) {
							mapDocNoY.put(docNo, String.valueOf(Integer.parseInt(dao.chkData(mapDocNoY.get(docNo))) + 1));
						} else {
							mapDocNoY.put(docNo, "1");
						}
					}
				}
				for (Map.Entry<String, String> entry : mapDocNoY.entrySet()) {
					docNo = entry.getKey();
					String value = entry.getValue();
					if (!dao.chkData(docNo).equals("")) {
						data = dao.findDataSql("SELECT COUNT(DOC_NO) AS NUM FROM " + this.schema + ".ACC6_EXPENSE_CHEQUE WHERE DOC_NO = '" + docNo + "'");
						String num =  dao.chkData(data.get("NUM"));
						Acc6ExpenseBean aeb = new Acc6ExpenseBean();
						aeb.setDocNo(docNo);
						if (value.equals(num)) {
							aeb.setExpenseStatus("Y");
						}
						aeb.setUpdatedBy("BAAC");
						aeb.setUpdatedDate("(SYSDATE)");
						dao.update(aeb);
					}
				}
			}
			this.message(request).setMsgCode("I002");
			conn.commit();
		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException eSQL) {
				eSQL.printStackTrace();
			}
			this.message(request).setMsg("E", e.toString() + ":" + dao.getMessage(), e.getStackTrace());
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				dao = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
			this.search(request);
		}
		return this.url;
	}
}
